// 产成品入库公共类
try {
	Type.registerNamespace('INVCOUNTUtil');
	INVCOUNTUtil.updateScanNumForList = function(pkitem) {
			// 回写扫描数量listvo
			condition = {
				"pkitem": pkitem
			}
			NCMMPubUtil.queryVOByConditions(INVCOUNTSCANVO, condition, function(scandata) {
				var scanednum = 0;
				if(scandata == null || scandata == "" | typeof(scandata) == 'undefined' || eval(scandata).length < 1) {
					//如何扫描记录为空，说明删除了所有的扫描记录,已扫描数量置为空
					scanednum = "";
					//return;
				} else {
					var scanvos = eval(scandata);
					for(var i = 0; i < scanvos.length; i++) {
						scanednum = NCMMPubUtil.getSumScanedNum(scanednum, scanvos[i]["scansinglenum"]);
					}
				}
				NCMMPubUtil.queryVOByConditions(INVCOUNTVO, condition, function(data) {
					if(data == null || data == "" | typeof(data) == 'undefined' || eval(data).length < 1)
						return;
					var vos = eval(data);
					//处理反斜杠特殊字符
					//vos[0] = NCMMPubUtil.htmlspecialjson2UI(vos[0]);
					vos[0]["scannum"] = scanednum.toString();
					var attris = [];
					attris.push(INVCOUNTVO.SCANNUM);
					NCMMPubUtil.updateVOWithAttris(INVCOUNTVO, vos[0], attris);
				});
			});
		}
		// 提交的时候判断是否还存在相同来源的扫描记录
	INVCOUNTUtil.checkOtherScanRecord = function(pkitem) {
		var flag = false;
		conditionForScan = {
			"pkitem": pkitem
		}
		NCMMPubUtil.queryVOByConditions(INVCOUNTSCANVO, conditionForScan, function(data) {
			if(data != null && data != "") {
				data = eval(data);
				if(data.length > 1) {
					// $alert("当前记录存在其他来源相同的扫描记录，不能单独提交！");
					flag = true;
					return flag;
				}
			}
		});
		return flag;
	}

	// 由主数量和换算率计算数量
	INVCOUNTUtil.getNastum = function(nnum, vchangerate) {
		if(nnum == null || nnum == "") {
			nnum = "0.00000";
		} else {
			nnum = parseFloat(nnum);
		}
		if(vchangerate == null || vchangerate == "") {
			vchangerate = "1.00000";
			var nastum = nnum / vchangerate;
		} else {
			var vchangearray = vchangerate.split("/");
			if(vchangearray == null || vchangearray.length != 2)
				return nnum;
			var up = parseFloat(vchangearray[0]);
			var down = parseFloat(vchangearray[1]);
			if(up == null || down == null)
				return nnum;
			var nastum = (nnum * down) / up;
		}
		return nastum;
	}

	// 由数量和换算率计算主数量
	INVCOUNTUtil.getNum = function(nastnum, vchangerate) {
			if(nastnum == null || nastnum == "") {
				nastnum = "0.00000";
			} else {
				nastnum = parseFloat(nastnum);
			}
			if(vchangerate == null || vchangerate == "") {
				vchangerate = "1.00000";
				var num = nastnum * vchangerate;
			} else {
				var vchangearray = vchangerate.split("/");
				if(vchangearray == null || vchangearray.length != 2)
					return nastnum;
				var up = parseFloat(vchangearray[0]);
				var down = parseFloat(vchangearray[1]);
				if(up == null || down == null)
					return nastnum;
				var num = (nastnum * up) / down;
			}
			return num;
		}
		//处理精度
	INVCOUNTUtil.processScale = function(jsonarray, numkeys, measurekey) {
			if(!NCMMPubUtil.isTableExist(MeasdocVO) || jsonarray == null || jsonarray == "" || jsonarray == "[]") {
				return;
			}
			for(var i = 0; i < jsonarray.length; i++) {
				var json = jsonarray[i];
				var scale = INVCOUNTUtil.getScaleDigit(json[measurekey]);
				if(scale == null || scale == "") {
					continue;
				}
				for(var j = 0; j < numkeys.length; j++) {
					var numStr = json[numkeys[j]];
					if(numStr != null && numStr != "") {
						var num = parseFloat(numStr);
						json[numkeys[j]] = num.toFixed(scale);
					}
				}
			}
		}
		//处理分组界面的精度
	INVCOUNTUtil.processGroupScale = function(jsonarray, headnumkeys, numkeys, measurekey) {
			if(!NCMMPubUtil.isTableExist(MeasdocVO) || jsonarray == null || jsonarray == "" || jsonarray == "[]") {
				return;
			}
			for(var i = 0; i < jsonarray.length; i++) {
				var json = jsonarray[i];
				var rowjsons = json["row"];
				if(rowjsons == null || rowjsons == "" || rowjsons == "[]") {
					continue;
				}
				//取扫描记录第一个取单位，有针对性处理，此时同一个单据行的所有扫描记录的单位应该是一样的
				var scale = INVCOUNTUtil.getScaleDigit(rowjsons[0][measurekey]);
				if(scale == null || scale == "") {
					continue;
				}
				//处理分组的表头数量字段，也使用表体的单位进行处理即可
				for(var m = 0; m < headnumkeys.length; m++) {
					var sumNumStr = json[headnumkeys[m]];
					if(sumNumStr != null && sumNumStr != "") {
						var sumNum = parseFloat(sumNumStr);
						json[headnumkeys[m]] = sumNum.toFixed(scale);
					}
				}
				//以此处理表体的每个数据的每个数字字段
				for(var k = 0; k < rowjsons.length; k++) {
					for(var j = 0; j < numkeys.length; j++) {
						var numStr = rowjsons[k][numkeys[j]];
						if(numStr != null && numStr != "") {
							var num = parseFloat(numStr);
							rowjsons[k][numkeys[j]] = num.toFixed(scale);
						}
					}
				}
			}
		}
		//设置数字精度
	INVCOUNTUtil.getScaleNum = function(numStr, pk_measure) {
			var scale = INVCOUNTUtil.getScaleDigit(pk_measure);
			if(scale == null || scale == "") {
				return numStr;
			}
			var num = parseFloat(numStr);
			return num.toFixed(scale);
		}
		//获取单位精度
	INVCOUNTUtil.getScaleDigit = function(pk_measure) {
			if(!NCMMPubUtil.isTableExist(MeasdocVO)) {
				return null;
			}
			var scale = "";
			var wheresql = "where pk_measdoc='" + pk_measure + "'"
			NCMMPubUtil.queryVO(MeasdocVO, wheresql, function(data) {
				if(data != null && data != "" && data != "[]") {
					var meajson = $stringToJSON(data);
					scale = meajson[0].bitnumber;
				}
			});
			return scale;
		}
		//校验输入数量的精度
	INVCOUNTUtil.validateNumScale = function(numStr, pk_measure) {
			var returnflag;
			var scale = INVCOUNTUtil.getScaleDigit(pk_measure);
			if(scale == null || scale == "") {
				returnflag = true;
				return returnflag;
			}
			var strs = numStr.split(".");
			if(strs.length == 1) {
				returnflag = true;
			} else if(strs.length == 2 && strs[1].length <= scale) {
				returnflag = true;
			} else {
				returnflag = false;
			}
			return returnflag;
		}
		//判断输入的字符串是否是数字，包括正、负、0
	INVCOUNTUtil.isNumber = function(inputstr) {
		var zregex = /^\d+(\.\d*)?$/;
		var fregex = /^((-\d*(\.\d*)?)|(0+(\.0*)?))$/;
		if(inputstr == null || inputstr == "") {
			return false;
		}
		if(!zregex.test(inputstr) && !fregex.test(inputstr)) {
			return false;
		}
		return true;
	}
	INVCOUNTUtil.getDefaultCondition = function() {
			var json = {};
			var stockorg = $cache.read("defaultstockorg") ? $cache.read("defaultstockorg") : "";
			if(stockorg != "") {
				stockorg = $stringToJSON(stockorg);
				stockorg = stockorg["pk_stockorg"];
			}
			var stordoc = $cache.read("defaultstordoc") ? $cache.read("defaultstordoc") : "";
			if(stordoc != "") {
				stordoc = $stringToJSON(stordoc);
				stordoc = stordoc["pk_stordoc"];
			}
			if(stockorg == "") {
				$toast("下载前请先进行业务设置");
				return null;
			}
			json["stockorg"] = stockorg;
			json["stordoc"] = stordoc;
			return json;
		}
		/***
		 *提交扫描记录到NC端 
		 * @param {Object} records
		 * @param {Object} billinfos
		 * @param {Object} callback
		 */
	INVCOUNTUtil.submitdataToNC = function(records, billinfos, callback) {
			NCMMDBUtil.testNCConnection(function(data) {
				if(data == false || data == "false") {
					$toast("连接服务器失败，无法提交！");
					return;
				}
				// 连接成功开始提交
				// $js.showLoadingBar();
				// 提交数据
				//$alert(billinfos);
				NCMMDBUtil.submitLocaldataToNC("4Rsave", billinfos, function(data) {
					if(data == null || data == "") {
						$alert("上传数据失败，请检查");
					} else {
						if(data.return != null && data.return != "") {
							if(data.return.returnFlag == 1) {
								// 返回成功，说明提交成功
								// 删除本地扫描数据
								// $js.hideLoadingBar();
								for(var index = 0; index < records.length; index++) {
									NCMMPubUtil.deleteVO(INVCOUNTSCANVO, records[index]);
									condition = {
										"pkitem": records[index]["pkitem"]
									};
									NCMMPubUtil.queryVOByConditions(INVCOUNTVO, condition, function(data) {
										if(data == null || data == "" | typeof(data) == 'undefined' || data.length < 1)
											return;
										var vos = eval(data);
										if(vos == null || vos.length < 1)
											return;
										NCMMPubUtil.deleteVO(INVCOUNTVO, vos[0]);
									});
								}
								if(callback != null) {
									callback();
								}
							} else {
								$alert($jsonToString(data));
								return;
							}
						} else {
							$alert($jsonToString(data));
							return;
						}
					}
				})
			});
		}
		//处理扫描记录持久化相关逻辑
	INVCOUNTUtil.persistRecord = function(json) {
		// 保存本条数据到本地数据库
		if(json["pkscan"] == "" || json["pkscan"] == null) {
			// 如果没有保存过就保存
			json["pkscan"] = getPKScan();
			NCMMPubUtil.insertVO(INVCOUNTSCANVO, json);
		} else {
			//var pkscan = json["pkscan"];
			//var isvoexist = NCMMPubUtil.isScanVOExistByPK(INVCOUNTSCANVO, pkscan)
			//if(!isvoexist) {
			// 在扫描记录界面删除后再跳回采集页面，pkscan不为空，但此时数据已经被删除
			//$alert("当前记录在扫描记录中已经被删除，请重新采集！");
			//return;
			//}
			// 如果保存过就更新
			NCMMPubUtil.updateVO(INVCOUNTSCANVO, json);
		}
		INVCOUNTUtil.updateScanNumForList(json["pkitem"]);
	}

	// 将扫描记录转换为提交NC的数据
	INVCOUNTUtil.changeVOTOBillInfos = function(vos) {
		if(vos == null || vos.length < 1) {
			return;
		}
		var bpks = [];
		var combinedvos = [];
		// 处理扫描数量，合并vo
		for(var i = 0; i < vos.length; i++) {
			// 来源id+批次号作为分单合并数量维度
			var matchpk = vos[i]["pkitem"] + vos[i]["vbatchcode"];
			if(bpks.indexOf(matchpk) == -1) {
				// 行id集合中不存在
				bpks.push(matchpk);
				if(vos[i].serialno != null && vos[i].serialno != "") {
					vos[i]["bbitems"] = [{
						"serialno": vos[i].serialno,
						"num": vos[i].scansinglenum
					}];
				}
				combinedvos.push(vos[i]);

			} else {
				// 如果matchpk在集合中存在，则合并扫描数量
				var currentscanednum = vos[i]["scansinglenum"];
				for(var j = 0; j < combinedvos.length; j++) {
					var combinedpk = combinedvos[j]["pkitem"] + combinedvos[j]["vbatchcode"];
					if(matchpk == combinedpk) {
						var bbitems = combinedvos[j]["bbitems"];
						if(bbitems != null && vos[i].serialno != null && vos[i].serialno != "") {
							bbitems.push({
								"serialno": vos[i].serialno,
								"num": vos[i].scansinglenum
							});
						}
						var scanednum = combinedvos[j]["scansinglenum"];
						combinedvos[j]["scansinglenum"] = NCMMPubUtil.getSumScanedNum(scanednum, currentscanednum);
						break;
					}
				}
			}
		}
		// 把合并的vo组装成billinfos的格式，用于提交数据
		var billinfos = createBillInfoForScanList(combinedvos);
		return billinfos;
	}

	// 用于上传创建billinfos
	function createBillInfoForScanList(vos) {
		var billinfos = [];
		var pkheads = [];
		var head = {};
		var item = {};
		var items;
		// 相同的表头合并表体
		for(var i = 0; i < vos.length; i++) {
			var pk_head = vos[i]["pkhead"];
			if(pkheads.indexOf(pk_head) == -1) {
				pkheads.push(pk_head);
				head = getHeadForScanList(vos[i]);
				item = getItemForScanList(vos[i]);
				items = [];
				items.push(item);
				var billinfo = {
					"head": head,
					"items": items
				};
				billinfo = {
					"billinfo": billinfo
				};
				billinfos.push(billinfo);
			} else {
				item = getItemForScanList(vos[i]);
				items.push(item);
			}
		}
		return billinfos;
	}

	function getHeadForScanList(vo) {
		var json = {};
		json["pk_head"] = vo.pkhead;
		// json["ts_h"] = vo["hts"];
		//仓库
		json["storcode"] = vo.pk_stordoc;
		return json;
	}

	function getItemForScanList(vo) {
		var item = {};
		item["pk_item"] = vo.pkitem;
		item["pk_material"] = vo.pkmaterial;
		item["pk_measdoc"] = vo.pk_measdoc;
		// item["ts_b"] = vo["bts"];
		//批次
		item["vbatchcode"] = vo.vbatchcode;
		//货位
		item["pk_rack"] = vo.pk_rack;
		//支持序列号
		if(NCMMPubUtil.isNotEmpty(vo.bbitems)) {
			var bbitems = [];
			for(var i = 0; i < vo.bbitems.length; i++) {
				var bbitem = {};
				bbitem["bbitem"] = {
					"vsncode": vo.bbitems[i].serialno,
					"ncountnum": vo.bbitems[i].num == "" ? "1.00000" : vo.bbitems[i].num
				};
				bbitems.push(bbitem);
			}
			item["bbitems"] = bbitems;
		}
		//盘点主数量
		item["ncountnum"] = vo.scansinglenum == "" ? "1.00000" : vo.scansinglenum;
		item = {
			"item": item
		};
		return item;
	}
	//处理下单引号
	INVCOUNTUtil.htmlsqmchars2UI = function(s) {
		if(s == null || s == NaN)
			return s;

		if(typeof(s) == "string" && s != "") {
			s = s.replace(/[']?/mg, function(tokens, index, currentStr) {
				if(tokens.charCodeAt(0) == 39) {
					return tokens + tokens;
				}
				return tokens;
			});
		}
		return s;
	};
	INVCOUNTUtil.processBillDataFromNC = function(VOClass, appbillname, condition, callback) {
		$js.showLoadingBar({
			msg: "正在连接服务器..."
		});
		var host = $cache.read('host');
		var port = $cache.read('port');
		$app.checkNetWorkReachable(host, port, function(param, args) {
			if(args.is_reachable == 'true') {
				$app.showLoadingBar({
					msg: "正在下载……"
				});
				NCMMDBUtil.loadNCBaseData(INVCOUNTVO, INVCOUNTVO, NCMMHttpUtil.BILL, condition, function(data) {
					//如果没有从NC端下载到数据，则本地记录不更新
					if(data == null) {
						$js.hideLoadingBar();
						$toast("没有获取到符合条件的订单");
						return;
					}
					if(data != null && typeof(data) == 'string') {
						$js.hideLoadingBar();
						$toast("下载失败：" + data);
						return;
					}
					//										$alert("process data=" + $jsonToString(data));
					// 如果没有信息直接返回
					var billinfos = data.billinfos || {};
					var props = Object.getOwnPropertyNames(billinfos) || [];
					if(props.length == 0) {
						if($isJSONObject(data)) {
							$js.hideLoadingBar();
							$toast("没有下载到【" + appbillname + "】");
						} else {
							$js.hideLoadingBar();
							$toast(data);
						}
						return;
					}
					//下载数据的条数
					//var vocount = NCMMDBUtil.getBillCount(data);
					// 把NC数据拉平
					var billinfos_local = [];
					billinfos_local = processScanNumForList(data);
					// 清空本地表记录
					NCMMDBUtil.clearAllOldData(VOClass, null);
					//billinfos_local = NCMMMOUtil.parseNCData2Local(billinfos);
					//					$alert("billinfos_local=" + $jsonToString(billinfos_local));
					// TODO 执行拓展服务insert操作
					var attrs = VOClass.prototype.getAllAttrs();
					var fields = attrs.map(function(row, i, arr) {
						return row.name;
					});

					var valueMapList = Array.prototype.map.call(billinfos_local, function(row, i, arr) {
						var billinfo_local = $stringToJSON((row || {}));
						var values = attrs.map(function(attr, i, array) {
							var fname = attr.name;
							if(!!billinfo_local[fname]) {
								if(billinfo_local[fname] != "" && typeof(billinfo_local[fname]) == "string") {
									billinfo_local[fname] = NCMMPubUtil.htmlspecialchars2sqliteex(billinfo_local[fname]);
								}
								return billinfo_local[fname];
							} else {
								if(attr.type == NCMMPubUtil.VALUE_TYPE_INTEGER) {
									return 0;
								} else if(attr.type == NCMMPubUtil.VALUE_TYPE_REAL) {
									return 0.0;
								} else {
									return "";
								}
							}
						});
						return values;
					});

					var sum = valueMapList.length;
					//					$alert("valueMapList=" + $jsonToString(valueMapList));

					$app.replaceBatch({
						db: NCMMPubUtil.DatabaseName,
						table: VOClass.prototype.getTableName(),
						fields: fields,
						values: valueMapList,
						callback: function(args_null, args) {
							if(args.code == '1000' || args.code == 1000) {
								$js.hideLoadingBar();
								$toast("【" + appbillname + "】下载了【" + sum + "】条数据。");
								if(callback) {
									callback(sum);
								}
							} else {
								$js.hideLoadingBar();
								$js.toast("【" + appbillname + "】下载异常");
								if(callback) {
									callback(null);
								}
							}
						}
					});

				});

			} else {
				$js.hideLoadingBar();
				$js.toast("下载失败请检查网络设置！");
			}
		});

	};

	function processScanNumForList(vos) {
		var billdatas = [];
		var json = {};
		var existpkitems = [];
		var scannumdatas = [];
		// 更新数据前在本地数据库查找扫描数量大于0的
		wheresql = "where scannum > 0";
		NCMMPubUtil.queryVO(INVCOUNTVO, wheresql, function(datas) {
			if(datas != null) {
				datas = eval(datas);
				scannumdatas = datas;
				if(datas.length > 0) {
					for(var index = 0; index < datas.length; index++) {
						// 放到一个json数组中
						json[(datas[index])["pkitem"]] = datas[index];
					}
				}
			}
		});
		var billinfos = vos.billinfos;
		for(var i = 0; i < billinfos.length; i++) {
			// 有多少个子项插入多少个vo
			var items = billinfos[i].billinfo.items;
			for(var j = 0; j < items.length; j++) {
				var billdata = $.extend({}, items[j].item, billinfos[i].billinfo.head);
				var pkitem = billdata["pkitem"];
				if(NCMMPubUtil.isNotEmpty(json[pkitem])) {
					existpkitems.push(pkitem);
					// 如果要下载的数据包含了本地有扫描记录的数据则更新扫描数量后再插入
					billdata["scannum"] = json[pkitem]["scannum"];
				}
				billdatas.push(billdata);
			}
		}
		for(var i = 0; i < scannumdatas.length; i++) {
			if(existpkitems.indexOf(scannumdatas[i]["pkitem"]) == -1) {
				billdatas.push(scannumdatas[i]);
			}
		}
		return billdatas;
	}
} catch(e) {
	$e(e);
}